//
//  cvprocess.m
//  e-glue-pyobjc
//
//  Created by Leonardo Dinnouti on 02/10/09.
//  Copyright 2009 Home. All rights reserved.
//

// opencv includes
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>

// klt includes
#include "pnmio.h"
#include "klt.h"

// e-glue includes
#include "egluesh.h"
#include "egdebug.h"

#import <ImageIO/ImageIO.h>
#import <CoreGraphics/CGImage.h>
//#import <CoreGraphics/CGImageDestination.h>
#import <Foundation/NSURL.h>
#import "cvprocess.h"


@implementation cvprocess

@synthesize leftImage;
@synthesize rightImage;

/**
 * Only testing.
 */
- (void)hello {
    NSLog(@"Hello world!");
}


/**
 * It is a stub between C and Objective-C
 * @param dstImage path to record destination file.
 */
- (int)glueImages:(NSString*)dstImage {
    NSLog(@"entering glueImages");
    NSLog(@"leftImage = %s", leftImage.UTF8String);
    NSLog(@"rightImage = %s", rightImage.UTF8String);
    egGlueImage(leftImage.UTF8String, rightImage.UTF8String, dstImage.UTF8String);
    NSLog(@"exiting glueImages");
    return 0;
}

/**
 * Save a image into a local file system
 */
- (BOOL)saveImage:(CGImageRef)image imagePath:(NSString*)imagePath {
    BOOL status = NO;
    NSError* outError;
    NSURL*             url = [NSURL fileURLWithPath:imagePath];
    CGImageDestinationRef myImageDest =
    CGImageDestinationCreateWithURL((CFURLRef)url,
                                    (CFStringRef)@"kUTTypeJPEG", 1, nil);
    // Make sure the image destination exists before continuing.
    if (myImageDest==nil) {
        NSLog(@"Image creation error.");
        if (status==NO) {
            outError = [NSError errorWithDomain:NSCocoaErrorDomain
                                            code:NSFileWriteUnknownError
                                        userInfo:nil];
        }
        return status;
    }
    
    NSDictionary*      myOptions = NULL;
    CFStringRef       myKeys[2];
    CFTypeRef         myValues[2];
    
    // Set up options if you want them. The options here are for caching the image
    // in a decoded form and for using floating-point values if the image
    // format supports them.
    myKeys[0] = kCGImageSourceShouldCache;
    myValues[0] = (CFTypeRef)kCFBooleanTrue;
    myKeys[1] = kCGImageSourceShouldAllowFloat;
    myValues[1] = (CFTypeRef)kCFBooleanTrue;
    // Create the dictionary
    myOptions = CFDictionaryCreate(NULL, (const void **) myKeys,
                                   (const void **) myValues, 2,
                                   &kCFTypeDictionaryKeyCallBacks,
                                   &kCFTypeDictionaryValueCallBacks);
    
    // Add the image to the destination using previously saved options.
    CGImageDestinationAddImage(myImageDest, image, myOptions);
    // Finalize the image destination.
    status = CGImageDestinationFinalize(myImageDest);
    // Release the image as soon as you no longer need it.
    CGImageRelease(image);
    
    return status;
    
}


@end
